package com.education.platform.api.config;


import com.alibaba.fastjson.JSON;
import com.education.platform.api.constants.RedisCacheConstant;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.entity.UserBaseDO;

/**
 * 用户信息
 */
public class ThreadUser {


    private static final ThreadLocal<String> USER_JSON_STR=new InheritableThreadLocal<>();
    private static final ThreadLocal<String> USER_TOKEN=new InheritableThreadLocal<>();

    private ThreadUser(){}
    public static void setUserJson(String userJson){
        USER_JSON_STR.set(userJson);
    }
    public static String getUserJson(){
        return USER_JSON_STR.get();
    }
    public static void removeUser(){
        USER_JSON_STR.remove();
        USER_TOKEN.remove();
    }
    public static <T> T getUser(Class<T> clazz){
        if(StringUtils.isEmpty(USER_JSON_STR.get())){
            throw new BusinessException("未获取到登录用户");
        }
        return JSON.parseObject(USER_JSON_STR.get(),clazz);
    }
    public static Integer getUserId(){
        UserBaseDO appUser = getUser( UserBaseDO.class);
        return appUser.getId();
    }
    public static String getUserName(){
        UserBaseDO appUser = getUser( UserBaseDO.class);
        return appUser.getNickName();
    }

    public static void setUserTokenRdisKey(String token){
        USER_TOKEN.set(token);
    }
    public static String getUserTokenRedisKey(){
        return USER_TOKEN.get();
    }
    public static boolean isLogin(){
       return StringUtils.isEmpty(USER_JSON_STR.get())?false:true;
    }

    public static String getRequestToken(){
        String tokenRedisKey = getUserTokenRedisKey();
        if(StringUtils.isEmpty(tokenRedisKey)){
            throw new BusinessException("未获取到登录用户");
        }
        return tokenRedisKey.substring(tokenRedisKey.indexOf( RedisCacheConstant.KEY_APP_TOKEN)+RedisCacheConstant.KEY_APP_TOKEN.length()) ;
    }
}
